﻿var currentSong;

var youtubeBaseUrl = 'http://gdata.youtube.com/feeds/api/videos?q=';
var youtubeBaseUrlTrailer = '&max-results=3&alt=json-in-script&callback=?';

function manageSong() {
	$('body').hide();
	currentSong = getSong(selectedSong);
	$('#title').append(currentSong.track_name);
	$('#artist').append(currentSong.artist_name);
	$('#album').append(currentSong.album_name);
	var numStars = Math.round(currentSong.track_rating / 20);
	var rating = $('#rating');
	for(i=0; i<numStars; i++) {
		rating.append($('<img src="img/rating.png"/>'));
	}
	$('#songPoster').attr('src', currentSong.album_coverart_100x100);
	var buyUrl = 'http://www.amazon.com/gp/aw/s/ref=is_box_?k=' + (currentSong.artist_name + ' ' + currentSong.album_name).replace(/ /g, "+");
	$('#buy').attr('href', buyUrl);
	var youtubeUrl = youtubeBaseUrl + (currentSong.artist_name + '' + currentSong.track_name).replace(/ /g, "+") + youtubeBaseUrlTrailer;
	$.getJSON(youtubeUrl, youtubeSearchCallback);
	var lyricsUrl = 'http://api.musixmatch.com/ws/1.1/track.lyrics.get' + "?apikey=" + musixmatchApiKey + "&format=jsonp" + "&track_id=" + currentSong.track_id + "&callback=?";
	console.log(lyricsUrl);
	$.getJSON(lyricsUrl, lyricsGetCallback);
}

function lyricsGetCallback(data) {
	var lyrics = data.message.body.lyrics.lyrics_body;
	$('#lyrics').append(lyrics);
}

function youtubeSearchCallback(data) {
	console.log('ciao');
	var thumbnail;
	var urlVideo;
	var entries = data.feed.entry;
	//$.each(entries, function(index, entry) {
	for(i=0;i<entries.length; i++) {
		thumbnail = entries[i].media$group.media$thumbnail[1].url;
		video = entries[i].link[0].href;
		//video
		//$('#video' + i).append('<a data-transition="none" target="_blank" href="' + video + '"><img class="youtube" src="' + thumbnail + '"/></a>');
		$('#video' + i).append('<div><a target="_blank" href="' + video + '"><img class="youtube" style="background-image:url(' + thumbnail + ')" src="img/play-overlay.png" /></a></div>');
	}
	var facebookUrl = 'https://www.facebook.com/sharer/sharer.php?u=' + entries[0].link[0].href + '%26t=' + entries[0].title + '"';
	$('#facebook').attr('href', facebookUrl);
	$('body').show();
}

function getSong(id) {
    var found = false;
    var song;
    var i = 0;
    while(i<=songs.length && !found) {
        if(songs[i].track.track_id == id) {
            found = true;
            song = songs[i];
        }
        i++;
    }
    return song.track;
}
